import {
  http,
  processServerMovies
} from '../../../util/util.js'
const app = getApp()

Page({
  data: {
    movies: [],
    inTheatersUrl: "movie/in_theaters",
    comingSoonUrl: "movie/coming_soon",
    top250Url: "movie/top250",
    _currentUrl: '',
    _navigateTitle: '',
  },

  onLoad(options) {
    const category = options.category
    let url = app.baseUrl

    this.data._navigateTitle = category;

    switch (category) {
      case '即将上映':
        url = url + this.data.comingSoonUrl
        break
      case '正在热映':
        url = url + this.data.inTheatersUrl
        break
      case 'Top250':
        url = url + this.data.top250Url
        break
    }
    this.data._currentUrl = url
    http(url, this.processMoreMovieData)
  },

  onReady () {
    wx.setNavigationBarTitle({
      title: this.data._navigateTitle
    });
  },

  processMoreMovieData(data) {
    const movies = processServerMovies(data)
    const totalMovies = this.data.movies.concat(movies);
    this.setData({
      movies: totalMovies
    });
    wx.stopPullDownRefresh();
  },

  onPullDownRefresh(event) {
      this.data.movies = []
      http(this.data._currentUrl, this.processMoreMovieData)
   },
  onReachBottom(event) {
    const totalCount = this.data.movies.length;
    //拼接下一组数据的URL
    const nextUrl = this.data._currentUrl +
      "?start=" + totalCount + "&count=20";
    console.log(nextUrl)
    http(nextUrl, this.processMoreMovieData)
  }
})